package com.yc.url;

import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zwei
 * @create 2024-07-20 14:58
 */
public class Test2_url_urlconnection_httpurlconnection {
    private static Logger log = Logger.getLogger(Test2_url_urlconnection_httpurlconnection.class);

    public static void main(String[] args) throws IOException {
        //1.url类：url：统一资源定位符  +urlconnection
//        URL url=new URL("http://www.baidu.com");
//        URLConnection con=url.openConnection();
//
//        String contentType=con.getContentType();
//        long conlength=con.getContentLength();
//        log.info(contentType+"\t"+conlength);
//
//        //响应头没有  响应头的内容已经被解析变成了 con中的属性值
//        InputStream iis=con.getInputStream();
//
//        byte[]bs=new byte[10*1024];
//        ByteArrayOutputStream baos=new ByteArrayOutputStream();
//        int length=-1;
//        while ((length=iis.read(bs,0,bs.length))!=-1){
//            baos.write(bs,0,bs.length);
//        }
//        baos.flush();
//        byte[]bb=baos.toByteArray();
//        String str=new String(bb);
//        System.out.println(str);    //响应头  响应实体(HTML)

        //2.URL+HTTPURLConnection
        URL url=new URL("http://www.hyycinfo.com/");
        HttpURLConnection con= (HttpURLConnection) url.openConnection();
        //HTTPURLConnection是专门针对http协议  所以有很多http相关的属性
        con.setRequestProperty("HOST","www.hyycinfo.com");
        con.setRequestMethod("GET");

        //con.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0");

        con.setDoOutput(true);
        con.setDoInput(true);
        String contentType=con.getContentType();
        long conlength=con.getContentLengthLong();
        log.info(contentType+"\t"+conlength);

        InputStream iis=con.getInputStream();
        byte[]bs=new byte[10*1024];
        int length=-1;
        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        while (  ( length=iis.read(bs,0,bs.length))!=-1){
            baos.write(bs,0,length);
        }
        baos.flush();
        byte[]bb=baos.toByteArray();
        String str=new String(bb);
        System.out.println(str);    //响应头  响应实体(html)
    }
}
